#!/usr/bin/env python2
#
# Copyright (c) 2016,2018 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from string import Template

from jvpp_model import is_control_ping, is_dump, is_request, is_event, is_control_ping_reply


def generate_callback_facade(work_dir, model, logger):
    """ Generates callback facade """
    logger.debug("Generating JVpp callback facade for %s" % model.json_api_files)
    _generate_ifc(work_dir, model),
    _generate_impl(work_dir, model)
    _generate_callback(work_dir, model)


def _generate_ifc(work_dir, model):
    with open("%s/CallbackJVpp%s.java" % (work_dir, model.plugin_java_name), "w") as f:
        f.write(_IFC_TEMPLATE.substitute(
            plugin_package=model.plugin_package,
            json_filename=model.json_api_files,
            plugin_name=model.plugin_java_name,
            methods=_generate_ifc_methods(model)
        ))

_IFC_TEMPLATE = Template("""
package $plugin_package.callfacade;

/**
 * <p>Callback Java API representation of $plugin_package plugin.
 * <br>It was generated by jvpp_callback_facade_gen.py based on $json_filename.
 */
public interface CallbackJVpp${plugin_name} extends io.fd.jvpp.notification.EventRegistryProvider, java.lang.AutoCloseable {

    // TODO add send

$methods
}
""")


def _generate_ifc_methods(model):
    plugin_package = model.plugin_package
    methods = []
    for msg in model.messages:
        if is_control_ping(msg):
            # Skip control ping managed by jvpp registry.
            continue
        if not (is_dump(msg) or is_request(msg)):
            # Skip replies and messages that do not not have replies (e.g events/counters).
            continue
        template = _IFC_NO_ARG_METHOD_TEMPLATE
        if msg.has_fields:
            template = _IFC_METHOD_TEMPLATE
        methods.append(template.substitute(
            name=msg.java_name_lower,
            plugin_package=plugin_package,
            request=msg.java_name_upper,
            reply=msg.reply_java
        ))
    return "\n".join(methods)

_IFC_NO_ARG_METHOD_TEMPLATE = Template(
    """    void $name($plugin_package.callback.${reply}Callback callback) throws io.fd.jvpp.VppInvocationException;""")

_IFC_METHOD_TEMPLATE = Template(
    """    void $name($plugin_package.dto.$request request, $plugin_package.callback.${reply}Callback callback) throws io.fd.jvpp.VppInvocationException;""")


def _generate_impl(work_dir, model):
    with open("%s/CallbackJVpp%sFacade.java" % (work_dir, model.plugin_java_name), "w") as f:
        f.write(_IMPL_TEMPLATE.substitute(
            plugin_package=model.plugin_package,
            json_filename=model.json_api_files,
            plugin_name=model.plugin_java_name,
            methods=_generate_impl_methods(model)
        ))

_IMPL_TEMPLATE = Template("""
package $plugin_package.callfacade;

/**
 * <p>Default implementation of Callback${plugin_name}JVpp interface.
 * <br>It was generated by jvpp_callback_facade_gen.py based on $json_filename.
 */
public final class CallbackJVpp${plugin_name}Facade implements CallbackJVpp${plugin_name} {

    private final $plugin_package.JVpp${plugin_name} jvpp;
    private final java.util.Map<Integer, io.fd.jvpp.callback.JVppCallback> callbacks;
    private final $plugin_package.notification.${plugin_name}EventRegistryImpl eventRegistry = new $plugin_package.notification.${plugin_name}EventRegistryImpl();
    /**
     * <p>Create CallbackJVpp${plugin_name}Facade object for provided JVpp instance.
     * Constructor internally creates CallbackJVppFacadeCallback class for processing callbacks
     * and then connects to provided JVpp instance
     *
     * @param jvpp provided io.fd.jvpp.JVpp instance
     *
     * @throws java.io.IOException in case instance cannot connect to JVPP
     */
    public CallbackJVpp${plugin_name}Facade(final io.fd.jvpp.JVppRegistry registry, final $plugin_package.JVpp${plugin_name} jvpp) throws java.io.IOException {
        this.jvpp = java.util.Objects.requireNonNull(jvpp,"jvpp is null");
        this.callbacks = new java.util.HashMap<>();
        java.util.Objects.requireNonNull(registry, "JVppRegistry should not be null");
        registry.register(jvpp, new CallbackJVpp${plugin_name}FacadeCallback(this.callbacks, eventRegistry));
    }

    @Override
    public $plugin_package.notification.${plugin_name}EventRegistry getEventRegistry() {
        return eventRegistry;
    }

    @Override
    public void close() throws Exception {
        jvpp.close();
    }

    // TODO add send()

$methods
}
""")


def _generate_impl_methods(model):
    plugin_package = model.plugin_package
    methods = []
    for msg in model.messages:
        if is_control_ping(msg):
            # Skip control ping managed by jvpp registry.
            continue
        if not (is_dump(msg) or is_request(msg)):
            # Skip replies and messages that do not not have replies (e.g events/counters).
            continue
        template = _IMPL_NO_ARG_METHOD_TEMPLATE
        if msg.has_fields:
            template = _IMPL_METHOD_TEMPLATE
        methods.append(template.substitute(
            name=msg.java_name_lower,
            plugin_package=plugin_package,
            request=msg.java_name_upper,
            reply=msg.reply_java
        ))
    return "\n".join(methods)

_IMPL_NO_ARG_METHOD_TEMPLATE = Template(
    """    public final void $name($plugin_package.callback.${reply}Callback callback) throws io.fd.jvpp.VppInvocationException {
        synchronized (callbacks) {
            callbacks.put(jvpp.$name(), callback);
        }
    }
""")

_IMPL_METHOD_TEMPLATE = Template("""    public final void $name($plugin_package.dto.$request request, $plugin_package.callback.${reply}Callback callback) throws io.fd.jvpp.VppInvocationException {
        synchronized (callbacks) {
            callbacks.put(jvpp.$name(request), callback);
        }
    }
""")


def _generate_callback(work_dir, model):
    with open("%s/CallbackJVpp%sFacadeCallback.java" % (work_dir, model.plugin_java_name), "w") as f:
        f.write(_CALLBACK_TEMPLATE.substitute(
            plugin_package=model.plugin_package,
            json_filename=model.json_api_files,
            plugin_name=model.plugin_java_name,
            methods=_generate_callback_methods(model)
        ))

_CALLBACK_TEMPLATE = Template("""
package $plugin_package.callfacade;

/**
 * <p>Implementation of JVppGlobalCallback interface for Java Callback API.
 * <br>It was generated by jvpp_callback_facade_gen.py based on $json_filename.
 */
public final class CallbackJVpp${plugin_name}FacadeCallback implements $plugin_package.callback.JVpp${plugin_name}GlobalCallback {

    private final java.util.Map<Integer, io.fd.jvpp.callback.JVppCallback> requests;
    private final $plugin_package.notification.Global${plugin_name}EventCallback eventCallback;
    private static final java.util.logging.Logger LOG = java.util.logging.Logger.getLogger(CallbackJVpp${plugin_name}FacadeCallback.class.getName());

    public CallbackJVpp${plugin_name}FacadeCallback(final java.util.Map<Integer, io.fd.jvpp.callback.JVppCallback> requestMap,
                                      final $plugin_package.notification.Global${plugin_name}EventCallback eventCallback) {
        this.requests = requestMap;
        this.eventCallback = eventCallback;
    }

    @Override
    public void onError(io.fd.jvpp.VppCallbackException reply) {

        io.fd.jvpp.callback.JVppCallback failedCall;
        synchronized(requests) {
            failedCall = requests.remove(reply.getCtxId());
        }

        if(failedCall != null) {
            try {
                failedCall.onError(reply);
            } catch(RuntimeException ex) {
                ex.addSuppressed(reply);
                LOG.log(java.util.logging.Level.WARNING, java.lang.String.format("Callback: %s failed while handling exception: %s", failedCall, reply), ex);
            }
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onControlPingReply(final io.fd.jvpp.dto.ControlPingReply reply) {

        io.fd.jvpp.callback.ControlPingCallback callback;
        final int replyId = reply.context;
        synchronized(requests) {
            callback = (io.fd.jvpp.callback.ControlPingCallback) requests.remove(replyId);
        }

        if(callback != null) {
            callback.onControlPingReply(reply);
        }
    }

$methods
}
""")


def _generate_callback_methods(model):
    plugin_package = model.plugin_package
    methods = []
    for msg in model.messages:
        if is_dump(msg) or is_request(msg):
            continue
        if is_control_ping_reply(msg):
            # Skip control ping managed by jvpp registry.
            continue

        # Generate callbacks for all messages except for dumps and requests (handled by vpp, not client).
        template = _CALLBACK_METHOD_TEMPLATE
        if is_event(msg):
            template = _CALLBACK_EVENT_METHOD_TEMPLATE
        msg_name = msg.java_name_upper
        methods.append(template.substitute(
            message=msg_name,
            callback="%sCallback" % msg_name,
            plugin_package=plugin_package
        ))
    return "\n".join(methods)

_CALLBACK_METHOD_TEMPLATE = Template("""
    @Override
    @SuppressWarnings("unchecked")
    public void on${message}(final $plugin_package.dto.${message} reply) {

        $plugin_package.callback.$callback callback;
        final int replyId = reply.context;
        if (LOG.isLoggable(java.util.logging.Level.FINE)) {
            LOG.fine(java.lang.String.format("Received ${message} event message: %s", reply));
        }
        synchronized(requests) {
            callback = ($plugin_package.callback.$callback) requests.remove(replyId);
        }

        if(callback != null) {
            callback.on${message}(reply);
        }
    }
""")

_CALLBACK_EVENT_METHOD_TEMPLATE = Template("""
    @Override
    @SuppressWarnings("unchecked")
    public void on${message}($plugin_package.dto.${message} notification) {
        if (LOG.isLoggable(java.util.logging.Level.FINE)) {
            LOG.fine(java.lang.String.format("Received ${message} event message: %s", notification));
        }
        eventCallback.on${message}(notification);
    }
""")
